//
//  HMStatusViewModel.swift
//  WeiBo14
//
//  Created by HM on 16/3/6.
//  Copyright © 2016年 HM. All rights reserved.
//  cell --> HMStatusViewModel --> HMStatus

import UIKit
import YYText

class HMStatusViewModel: NSObject {

    // 当前视图模型引用的 status
    var status: HMStatus? {
        didSet{
            print("status didSet")
        }
    }
    
    // 当前发这条微博的用户的认证图标
    var verifiedImage: UIImage?
    // 会员图标
    var membershipImage: UIImage?
    
    // 转发数量
    var repostsCountStr: String?
    // 评论数量
    var commentsCountStr: String?
    // 点赞数量
    var attitudesCountStr: String?
    // 转发微博的内容.包含前面的昵称
    var retweetedText: String?
    // 格式化好的来源字符串
    var sourceText: String?
    // 原创微博显示的富文本内容
    var originalAttributedString: NSMutableAttributedString?
    // 原创微博的内容大小
    var originalAttrSize: CGSize?
    // 转发微博的富文本内容
    var retweetAttributedString: NSMutableAttributedString?
    
    // 创建时间字符串
    var createAtText: String? {
        get{
            return status?.createdDate?.dateDescription
        }
    }
    
    init(status: HMStatus) {
        super.init()
        self.status = status
        
        // 设置认证
        // 拿到 status 里面的认证类型,去生成对应的认证图标 
        
        let verifiedType = status.user?.verified ?? -1
        
        switch verifiedType {
        case 1:
            verifiedImage = UIImage(named: "avatar_vip")
        case 2,3,5:// 企业认证
            verifiedImage = UIImage(named: "avatar_enterprise_vip")
        case 220: // 达人
            verifiedImage = UIImage(named: "avatar_grassroot")
        default:
            verifiedImage = nil
        }
        
        // 设置会员图标
        if let mbrank = status.user?.mbrank where mbrank > 0 {
            membershipImage = UIImage(named: "common_icon_membership_level\(mbrank)")
        }
        
        // 计算转发评论赞的三个按钮显示的字符串
        // 先计算转发的内容
        
        repostsCountStr = stringWithCount(status.reposts_count, defaultString: "转发")
        commentsCountStr = stringWithCount(status.comments_count, defaultString: "评论")
        attitudesCountStr = stringWithCount(status.attitudes_count, defaultString: "赞")
        
        // 计算转发微博的内容
        // 判断如果有转发微昵称和转发微博内容的话,就去设置转发微博内容
        if let screenName = status.retweeted_status?.user?.screen_name, text = status.retweeted_status?.text {
            retweetedText = "@\(screenName):\(text)"
            retweetAttributedString = dealStatusText(retweetedText!)
        }else{
            retweetedText = "该微博已被删除,看什么看!"
        }
        
        // 处理来源的字符串
        dealSourceText(status.source)
        // 处理原创微博内容:表情字符串匹配,替换
        originalAttributedString = dealStatusText(status.text)
        // 设置内容最大的大小
        let maxSize = CGSize(width: SCREENW - 2 * HMStatusCellMargin, height: CGFloat(MAXFLOAT))
        // 初始化layout
        let layout = YYTextLayout(containerSize: maxSize, text: originalAttributedString)
        // 获取大小
        originalAttrSize = layout.textBoundingSize
    }
    
    /**
     // KaaaaAAAAA[炸鸡和啤酒]AAAAAA[带着微博去旅行]AAAA

    */
    
    /// 处理微博内容
    ///
    /// - parameter text: 微博内容
    private func dealStatusText(text: String?) -> NSMutableAttributedString? {
        guard let string = text else {
            return nil
        }
        
        // 原来的富文本
        let originalAttr = NSMutableAttributedString(string: string)
        
        // 匹配表情字符串
        // [中文数字英文]
        // memory是指取到该指针对应的值
        
        // 定义一个数组保存匹配结果
        var matchResults = [HMMatchResult]()
        // 定义正则表达式
        let regex = "\\[[a-zA-Z0-9\\u2E80-\\u9FFF]+\\]"
        // 匹配符合条件的表情字符串
        (string as NSString).enumerateStringsMatchedByRegex(regex) { (captureCount, captureString, captureRange, stop) -> Void in
            // 保存匹配的字符串和匹配的范围
            let matchResult = HMMatchResult(captureString: captureString.memory!, captureRange: captureRange.memory)
            matchResults.append(matchResult)
        }
        
        
        // 倒着遍历匹配的结果,替换表情
        for result in matchResults.reverse() {
            
            // 通过表情字符串找到对应的表情模型
            if let emoticon = HMEmoticonTools.sharedTools.emoticonWithChs(result.captureString as String) {
                
                // 通过字体大小取到图片显示的大小
                let imageWH = UIFont.systemFontOfSize(HMStatusContentFontSize).lineHeight
                
                // 生成图片
                let image = UIImage(named: "\(emoticon.folderName!)/\(emoticon.png!)", inBundle: HMEmoticonTools.sharedTools.emoticonsBundle, compatibleWithTraitCollection: nil)
                
                // 初始化 文字附件
                let attachment = HMTextAttachment()
                attachment.image = image
                attachment.bounds = CGRect(x: 0, y: -4, width: imageWH, height: imageWH)
                
                // 初始化 NSAttributedString -> 带有表情图片的attr
                let attr = NSAttributedString(attachment: attachment)
                
                // 将指定位置的文字字符串替换成上一步生成的表情字符串
                originalAttr.replaceCharactersInRange(result.captureRange, withAttributedString: attr)
            }
            
        }
        
        // 添加字体大小和颜色的属性
        originalAttr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(HMStatusContentFontSize), range: NSMakeRange(0, originalAttr.length))
        originalAttr.addAttribute(NSForegroundColorAttributeName, value: UIColor.darkGrayColor(), range: NSMakeRange(0, originalAttr.length))
        
//        // 给指定位置添加高亮文字
//        originalAttr.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSMakeRange(0, 1))
        
        // 匹配网址:([hH]ttp[s]{0,1})://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\-~!@#$%^&*+?:_/=<>.',;]*)?
        let urlRegex = "([hH]ttp[s]{0,1})://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\-~!@#$%^&*+?:_/=<>.',;]*)?"
        addHighLightedText(urlRegex, attributedString: originalAttr)
//        (originalAttr.string as NSString).enumerateStringsMatchedByRegex(urlRegex) { (count, captureString, captureRange, stop) -> Void in
//            originalAttr.addAttribute(NSForegroundColorAttributeName, value: RGB(r: 52, g: 105, b: 164), range: captureRange.memory)
//        }
        
        // 匹配@xxxx,中文,英文,数字,_,-
        let atRegex = "@[\\u2E80-\\u9FFFa-zA-Z0-9_\\-]+"
        addHighLightedText(atRegex, attributedString: originalAttr)
//        (originalAttr.string as NSString).enumerateStringsMatchedByRegex(atRegex) { (count, captureString, captureRange, stop) -> Void in
//            originalAttr.addAttribute(NSForegroundColorAttributeName, value: RGB(r: 52, g: 105, b: 164), range: captureRange.memory)
//        }
        
        // 匹配话题 : # 不能出现# #
        let topPicRegex = "#[^#]+#"
        addHighLightedText(topPicRegex, attributedString: originalAttr)
//        (originalAttr.string as NSString).enumerateStringsMatchedByRegex(topPicRegex) { (count, captureString, captureRange, stop) -> Void in
//            originalAttr.addAttribute(NSForegroundColorAttributeName, value: RGB(r: 52, g: 105, b: 164), range: captureRange.memory)
//        }
        

        
        return originalAttr
    }
    
    /// 根据正则表达式,添加高亮的文字
    ///
    /// - parameter regex:            正则表达式
    /// - parameter attributedString: 要添加高亮字符的富文本
    private func addHighLightedText(regex: String, attributedString: NSMutableAttributedString) {
        
        // 根据表达式匹配出范围,在指定的范围内,添加文字颜色
        (attributedString.string as NSString).enumerateStringsMatchedByRegex(regex) { (count, captureString, captureRange, stop) -> Void in
            
            attributedString.addAttribute(NSForegroundColorAttributeName, value: RGB(r: 52, g: 105, b: 164), range: captureRange.memory)
            
            // 初始化border
            let border = YYTextBorder(fillColor: RGB(r: 152, g: 206, b: 255), cornerRadius: 3)
            border.insets = UIEdgeInsetsZero
            // 初始化yytexthighlighted对象
            let highlighted = YYTextHighlight()
            // 将高亮的文字设置到userInfo里面去
            highlighted.userInfo = ["text": captureString.memory!]
            // 高亮的时候的文字颜色
            highlighted.setColor(RGB(r: 52, g: 105, b: 164))
            highlighted.setBackgroundBorder(border)
            
            attributedString.yy_setTextHighlight(highlighted, range: captureRange.memory)
            
        }
    }
    
    

    
    // 处理来源字符串
    func dealSourceText(source: String?){
        // <a href="http://weibo.com" rel="nofollow">新浪微博</a>
        
        guard let s = source else {
            return
        }
        
        // 截取中间字符串
        // 取到开始截取的位置
        if let startIndex = s.rangeOfString("\">")?.endIndex {
            // 取到结束截取的位置
            if let endIndex = s.rangeOfString("</")?.startIndex {
                sourceText = "来自 \(s.substringWithRange(startIndex..<endIndex))"
            }
        }
    }
    
    
    /// 通过数量计算该数量显示的文字
    ///
    /// - parameter count:         数量
    /// - parameter defaultString: 默认要显示文字(count=0的时候)
    ///
    /// - returns: <#return value description#>
    private func stringWithCount(count: Int, defaultString: String) -> String {
        /**
        以转发来说,如果有转发数据,那么就显示对应数量
        - 如果低于10000 --> 直接显示数字
        - 如果低于10900 --> 显示1万
        - 如果高于11000(12003) --> 显示 1.x 万
        */
        if count < 10000 {
            if count == 0 {
                return defaultString
            }else{
                return "\(count)"
            }
        }else{
            let result = CGFloat(count / 1000) / 10
            let resultStr = "\(result)万"
            
            if resultStr.containsString(".0") {
                return resultStr.stringByReplacingOccurrencesOfString(".0", withString: "")
            }
            return resultStr
        }
    }
}
